import { createApp } from "vue";
import App from "./App.vue";
import { createRouter, createWebHistory } from "vue-router";
import routes from "./router";
import store from "./store";
import Antd from "ant-design-vue";
import {
  exportLifeCycleHooks,
  qiankunWindow,
} from "@sh-winter/vite-plugin-qiankun/dist/helper";
import "ant-design-vue/dist/antd.css";

let app = null;
let router = null;

// 注意！插件里面的全局变量是挂载到 qiankunWindow 上面，qiankun的全局变量是挂载到 window上面的
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  render();
}

function render(props = {}) {
  const { container } = props;
  let basePath = qiankunWindow.__POWERED_BY_QIANKUN__
    ? import.meta.env.VITE_ROUTE_BASE_PATH
    : "/";

  app = createApp(App);
  router = createRouter({
    history: createWebHistory(basePath),
    routes,
  });
  app
    .use(router)
    .use(store)
    .use(Antd)
    .mount(container ? container.querySelector("#app") : "#app", true);
}

// 通过插件的exportLifeCycleHooks来导出生命勾子函数
exportLifeCycleHooks({
  /**
   * bootstrap 只会在微应用初始化的时候调用一次，下次微应用重新进入时会直接调用 mount 钩子，
   * 不会再重复触发 bootstrap; 可以在这里做一些全局变量的初始化，
   * 比如不会在 unmount 阶段被销毁的应用级别的缓存等
   */
  bootstrap() {
    console.log("subapp bootstrap!");
  },
  mount(props) {
    render(props);
  },
  unmount() {
    app?.unmount();
    app = null;
    router = null;
  },
  update() {
    console.log("subapp update!");
  },
});
